package hlhj.fhp.supreme.activitys

import android.annotation.SuppressLint
import android.app.ActivityOptions
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.AnimationDrawable
import android.graphics.drawable.Drawable
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.MediaStore
import android.support.annotation.RequiresApi
import android.support.v7.widget.LinearLayoutManager
import android.text.Html
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ImageSpan
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.*
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.onekeyshare.OnekeyShare
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.gyf.barlibrary.ImmersionBar
import com.hyphenate.EMCallBack
import hlhj.fhp.supreme.BaseAty
import hlhj.fhp.supreme.R
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.*
import com.hyphenate.chat.adapter.message.EMAVoiceMessageBody
import com.hyphenate.easeui.domain.EaseEmojicon
import com.hyphenate.easeui.model.EaseDefaultEmojiconDatas
import com.hyphenate.easeui.utils.EaseCommonUtils
import com.hyphenate.easeui.widget.EaseChatExtendMenu
import com.hyphenate.easeui.widget.EaseChatInputMenu
import com.hyphenate.easeui.widget.EaseVoiceRecorderView
import com.hyphenate.util.PathUtil
import com.liaoinstan.springview.container.DefaultHeader
import com.liaoinstan.springview.widget.SpringView
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import fhp.hlhj.giantfold.utils.LogUtil
import fhp.hlhj.giantfold.utils.ToastUtils
import hlhj.fhp.supreme.customview.DashangDialog
import hlhj.fhp.supreme.customview.Player
import hlhj.fhp.supreme.javabean.*
import hlhj.fhp.supreme.network.Urls
import hlhj.fhp.supreme.utils.*
import kotlinx.android.synthetic.main.activity_jie_pan_detail_aty.*
import kotlinx.android.synthetic.main.option_text.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.util.ArrayList
import java.util.HashMap


class JiePanDetailAty : BaseAty() {
    private lateinit var msgListener:EMMessageListener
    private lateinit var cameraFile: File
    private val messageLists=ArrayList<CustomMessage>()
    private lateinit var adp:BaseMultiItemQuickAdapter<CustomMessage,BaseViewHolder>
//    private val voicePlayers=HashMap<String,Player>()
    private var tempTime:Long=0
    private var toChatUsername=""
    private lateinit var animDrawable:AnimationDrawable
    private lateinit var player:Player
    private  var owner=""
    private var qnToken=""
    private lateinit var userInfo:UserInfoBean.DataBean
    private val REQUEST_CODE_CAMERA: Int=1
    private var roomId=""
    private val playingLists=HashMap<Int,Boolean>()
    private  var conversation:EMConversation?=null
    private val hisDatas=ArrayList<CustomMessage>()
    private val lastMessage=ArrayList<EMMessage>()
    private val handler= @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            LogUtil.logi("传戳来")
            adp.notifyDataSetChanged()
            recyclerview.scrollToPosition(messageLists.size-1)
        }
    }
    override fun getContentId(): Int {
        return R.layout.activity_jie_pan_detail_aty
    }

    var imgGetterFromProject: Html.ImageGetter = Html.ImageGetter { source ->
        var drawable: Drawable? = null
        val rId = Integer.parseInt(source)
        drawable = resources.getDrawable(rId)

        drawable!!.setBounds(0, 0, drawable!!.getIntrinsicWidth(),
                drawable!!.getIntrinsicHeight())
        drawable
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .statusBarColor(R.color.them_yellow)
                .init()
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        EventBus.getDefault().register(this)
    }
    override fun initView() {
        tv_title.text=intent.getStringExtra("name")
        userInfo=SPHelper.getUser(this) as UserInfoBean.DataBean
        roomId = intent.getStringExtra("roomId")
        toChatUsername=intent.getStringExtra("roomId")
        owner=intent.getStringExtra("owner")


        try {
            conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername,EMConversation.EMConversationType.ChatRoom)
        }catch (e:Exception){
            Log.e("fhpp","获取conversation失败")
        }
/*        Thread(Runnable {
            roomId = intent.getStringExtra("roomId")
            Log.e("fhppp","打开的id${roomId}")
            val group = EMClient.getInstance().groupManager().getGroupFromServer(roomId)
            if (group!=null){
                Log.e("fhppp","有拥有者${owner}---${group.owner}")
                owner = group.owner
                tv_title.postDelayed({ getMessgeHis() },200)
            }else{
                Log.e("fhppp","没有拥有者${owner}")
            }
        }).start()*/
        LogUtil.log("roomId${intent.getStringExtra("roomId")}")
        Log.e("fhppp","拥有者---------------${owner}")
        player= Player(seekBar);
        initAnim()
        initAdp()
        initInput()
        /*消息监听*/
        msgListener = object : EMMessageListener {
            override fun onMessageReceived(messages: List<EMMessage>) {
                LogUtil.logi("收到消息${messages.get(0)}来自${messages.get(0).to}")
                if (roomId.equals(messages[0].to.toString())){
                    for(i in 0..messages.size-1){
                        val message = CustomMessage()
                        message.message=messages[i]
                        message.type=when(messages[i].type){
                            EMMessage.Type.TXT->1
                            EMMessage.Type.IMAGE->2
                            EMMessage.Type.VOICE-> 3
                            EMMessage.Type.VIDEO->4
                            else->0
                        }
                        messageLists.add(message)
                        playingLists.put(messageLists.size,false)
                    }
                    handler.sendEmptyMessage(1)
                    LogUtil.logi("收到")
                }

                //收到消息
            }

            override fun onCmdMessageReceived(messages: List<EMMessage>) {
                LogUtil.logi("收到透传消息")
                //收到透传消息
            }

            override fun onMessageRead(messages: List<EMMessage>) {
                LogUtil.logi("消息已读")
                //收到已读回执
            }

            override fun onMessageDelivered(message: List<EMMessage>) {
                LogUtil.logi("消息已送达")
                //收到已送达回执
            }

            override fun onMessageRecalled(messages: List<EMMessage>) {
                LogUtil.logi("消息被撤回")
                //消息被撤回
            }

            override fun onMessageChanged(message: EMMessage, change: Any) {
                LogUtil.logi("消息有变动")
                //消息状态变动
            }
        }

        EMClient.getInstance().chatManager().addMessageListener(msgListener)

        /*获取消息记录*/
        getMessgeHis()
    }

    //获取消息记录
    private fun getMessgeHis() {
        if (conversation!=null){
            try {
//            val list = historyMessages.data
                val allMessages = conversation!!.allMessages
                val msgId = allMessages[0].msgId
                val tempHisDatas=ArrayList<CustomMessage>()
                for (i in 0..conversation!!.allMessages.size-1){
                    val emMessage = conversation!!.allMessages[i]
                    LogUtil.e("fhpp","消息从哪来${emMessage.from}房主是${owner}")
                    if (roomId.equals(emMessage.to)){
                        val message = CustomMessage()
                        message.message=emMessage
                        message.type=when(emMessage.type){
                            EMMessage.Type.TXT->{
                                if (emMessage.from.equals(EMClient.getInstance().currentUser)){
                                    11
                                }else{

                                    1
                                }

                            }

                            EMMessage.Type.IMAGE->{
                                if (emMessage.from.equals(EMClient.getInstance().currentUser)){
                                    21
                                }else{

                                    2
                                }
                            }
                            EMMessage.Type.VOICE-> {
                                if (emMessage.from.equals(EMClient.getInstance().currentUser)){
                                    31
                                }else{

                                    3
                                }
                            }
                            EMMessage.Type.VIDEO->{
                                if (emMessage.from.equals(EMClient.getInstance().currentUser)){
                                    41
                                }else{

                                    4
                                }
                            }
                            else->1
                        }
                        tempHisDatas.add(message)
                        hisDatas.add(message)
                    }
                }//添加到数据ADP中
                messageLists.addAll(0,tempHisDatas)
                handler.sendEmptyMessage(1)
                spView.header=DefaultHeader(this@JiePanDetailAty)
                spView.setListener(object :SpringView.OnFreshListener{
                    override fun onLoadmore() {
                    }

                    override fun onRefresh() {
                        val temp2HisDatas=ArrayList<CustomMessage>()
                        spView.onFinishFreshAndLoad()
                        Log.e("fhpp","已经存入的大小${hisDatas.size}---db总共大小${conversation!!.allMsgCount}")
                        if (conversation!!.allMessages.size<conversation!!.allMsgCount){
                            val nowSize = conversation!!.allMessages.size
                            lastMessage.addAll(conversation!!.allMessages)
                            Log.e("fhpp","开始大小${nowSize}")
                            val dbLists = conversation!!.loadMoreMsgFromDB(msgId, 5+nowSize)
                            dbLists.removeAll(lastMessage)
                            lastMessage.clear()
                            for (i in 0..dbLists.size-1){
                                val emMessage = dbLists[i]
                                if (roomId.equals(emMessage.to)){
                                    val message = CustomMessage()
                                    message.message=emMessage
                                    message.type=when(emMessage.type){
                                        EMMessage.Type.TXT->{
                                            if (emMessage.from.equals(EMClient.getInstance().currentUser)){
                                                11
                                            }else{

                                                1
                                            }

                                        }

                                        EMMessage.Type.IMAGE->{
                                            if (emMessage.from.equals(EMClient.getInstance().currentUser)){
                                                21
                                            }else{

                                                2
                                            }
                                        }
                                        EMMessage.Type.VOICE-> {
                                            if (emMessage.from.equals(EMClient.getInstance().currentUser)){
                                                31
                                            }else{

                                                3
                                            }
                                        }
                                        EMMessage.Type.VIDEO->{
                                            if (emMessage.from.equals(EMClient.getInstance().currentUser)){
                                                41
                                            }else{

                                                4
                                            }
                                        }
                                        else->1
                                    }
                                    temp2HisDatas.add(message)
                                    hisDatas.add(message)
                                }
                            }//添加到数据ADP中
                            messageLists.addAll(0,temp2HisDatas)
                            adp.notifyDataSetChanged()
                        }
                    }
                })
            }catch (e:Exception){
                LogUtil.e("fhpp","报了错${e.toString()}")
            }

        }

    }

    private fun initAnim() {
        animDrawable=AnimationDrawable()
        animDrawable.addFrame(resources.getDrawable(R.mipmap.ic_voice),200)
        animDrawable.addFrame(resources.getDrawable(R.mipmap.ic_voice1),200)
        animDrawable.addFrame(resources.getDrawable(R.mipmap.ic_voice2),200)
        animDrawable.addFrame(resources.getDrawable(R.mipmap.ic_voice3),200)
        animDrawable.isOneShot=false
    }

    private fun initAdp() {
        adp=object :BaseMultiItemQuickAdapter<CustomMessage,BaseViewHolder>(messageLists){
            init {
                addItemType(1,R.layout.chat_text_item)//别人文字
                addItemType(2,R.layout.chat_img_item)//别人图片
                addItemType(3,R.layout.chat_voice_item)//别人语音
                addItemType(4,R.layout.chat_video_item)//别人视频
                addItemType(11,R.layout.chat_text_item_self)//自己文字
                addItemType(21,R.layout.chat_img_item_self)//自己图片
                addItemType(31,R.layout.chat_voice_item_self)//自己声音
                addItemType(41,R.layout.chat_video_item_self)//自己视频
            }
            @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
            override fun convert(helper: BaseViewHolder?, item: CustomMessage?) {
                when(helper?.itemViewType){
                    0->{
                        LogUtil.logi("进来设置了0")
                    }
                    1->{
                        LogUtil.logi("进来设置了1")
//                        OkGo.post<HXBean>(Urls.BaseUrl+Urls.HX_USER)
///*                                .cacheKey("icon${item?.message?.from}")
//                                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
//                                .cacheTime(3600*1000)*/
//                                .headers("token", SPHelper.getToken(this@JiePanDetailAty))
//                                .params("hx_user_name",item?.message?.from)
//                                .execute(object :JsonCallBack<HXBean>(){
//                                    override fun onSuccess(response: Response<HXBean>?) {
//                                        val hxBean = response?.body()
//                                        if (hxBean?.code==1){
//                                            if (hxBean?.data!=null){
//                                                LogUtil.logi("头像${hxBean?.data.avatar}")
//                                                Glide.with(mContext).load(hxBean.data.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
//                                                helper?.setText(R.id.itemName,hxBean?.data.user_nickname)
//                                            }
//                                        }
//
//                                    }
//                                })


                        val messageBody = item?.message?.body as EMTextMessageBody
                        val itemContent = helper?.getView<TextView>(R.id.itemContent)
                        itemContent.text=messageBody.message
                        /*头像昵称*/
                        Glide.with(mContext).load(item?.message.getStringAttribute("userIcon")).dontAnimate().into(helper?.getView(R.id.itemIcon))
                        helper?.setText(R.id.itemName,item?.message.getStringAttribute("userName"))
                        if (helper?.adapterPosition==0){
                            helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                        }else{
                            if (MyUtils.secLeft(data[helper?.adapterPosition-1].message.msgTime,System.currentTimeMillis())>300){
                                helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                            }else{
                                helper?.setText(R.id.itemTime,"")
                            }
                        }
                        //处理表情
                        var tmpStr = itemContent.text.toString()
                        for (i in 0 ..EaseDefaultEmojiconDatas.emojis.size-1){
                            if (tmpStr.contains(EaseDefaultEmojiconDatas.emojis[i])){
//                                val tmpStr = itemContent.text.toString()
                                val emojiText = EaseDefaultEmojiconDatas.emojis[i]
                                var emji="<img src=\""+EaseDefaultEmojiconDatas.icons[i]+"\"/>"
                                tmpStr = tmpStr.replace(emojiText, emji)
                                LogUtil.logi("处理表情后${tmpStr}")
                            }
                        }
                        itemContent.text=Html.fromHtml(tmpStr,imgGetterFromProject,null)
                        /* ************************************************************/

                        if (item?.message.from.equals(owner)){
                            if (helper?.getView<TextView>(R.id.itemTime).text.isNotEmpty()){

                            }else{
                                helper?.setVisible(R.id.btGive,true)
                            }
                        }else{
                            helper?.setVisible(R.id.btGive,false)
                        }
                        val btGive = helper?.getView<TextView>(R.id.btGive)
                        if (helper?.adapterPosition==0){
                            helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                        }else{
                            if (MyUtils.secLeft(data[helper?.adapterPosition-1].message.msgTime,System.currentTimeMillis())>3000){
                                helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                            }else{
                                helper?.setText(R.id.itemTime,"")
                            }
                        }
                        btGive.setOnClickListener {
                            DashangDialog(mContext,3,item?.message.from.toInt()).show()
                        }
                    }
                    2->{
                        LogUtil.logi("进来设置了2")
//                        OkGo.post<HXBean>(Urls.BaseUrl+Urls.HX_USER)
//                                .headers("token", SPHelper.getToken(this@JiePanDetailAty))
//                                .params("hx_user_name",item?.message?.from)
//                                .execute(object :JsonCallBack<HXBean>(){
//                                    override fun onSuccess(response: Response<HXBean>?) {
//                                        val hxBean = response?.body()
//                                        if (hxBean?.code==1){
//                                            if (hxBean?.data!=null){
//                                                Glide.with(mContext).load(hxBean.data.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
//                                                helper?.setText(R.id.itemName,hxBean?.data.user_nickname)
//                                            }
//                                        }
//                                    }
//
//                                    override fun onCacheSuccess(response: Response<HXBean>?) {
//                                        super.onCacheSuccess(response)
//                                        val hxBean = response?.body()
//                                        if (hxBean?.code==1){
//                                            if (hxBean?.data!=null){
//                                                Glide.with(mContext).load(hxBean.data.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
//                                                helper?.setText(R.id.itemName,hxBean?.data.user_nickname)
//                                            }
//                                        }
//                                    }
//                                })

                        val messageBody = item?.message?.body as EMImageMessageBody
/*头像昵称*/
                        Glide.with(mContext).load(item?.message.getStringAttribute("userIcon")).dontAnimate().into(helper?.getView(R.id.itemIcon))
                        helper?.setText(R.id.itemName,item?.message.getStringAttribute("userName"))
                        val imageView = helper?.getView<ImageView>(R.id.itemImg)
                        imageView.setOnClickListener {
                                    val intent = Intent(this@JiePanDetailAty, ImagePreviewAty::class.java)
                                    intent.putExtra("img",messageBody.remoteUrl)
                                    startActivity(intent)
                                }
                        Glide.with(mContext)
                                .load(messageBody.thumbnailUrl)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .thumbnail(0.2f).into(imageView)
                        val message = item?.message
                        if (helper?.adapterPosition==0){
                            helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                        }else{
                            if (MyUtils.secLeft(data[helper?.adapterPosition-1].message.msgTime,System.currentTimeMillis())>3000){
                                helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                            }else{
                                helper?.setText(R.id.itemTime,"")
                            }
                        }
                        if (message.from.equals(owner)){
                            helper?.setVisible(R.id.btGive,true)
                        }else{
                            helper?.setVisible(R.id.btGive,false)
                        }
                    }
                    3->{
                        LogUtil.logi("进来设置了3")
//                        OkGo.post<HXBean>(Urls.BaseUrl+Urls.HX_USER)
//                                .cacheKey("icon${item?.message?.from}")
//                                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
//                                .headers("token", SPHelper.getToken(this@JiePanDetailAty))
//                                .params("hx_user_name",item?.message?.from)
//                                .execute(object :JsonCallBack<HXBean>(){
//                                    override fun onSuccess(response: Response<HXBean>?) {
//                                        val hxBean = response?.body()
//                                        if (hxBean?.code==1){
//                                            if (hxBean?.data!=null){
//                                                Glide.with(mContext).load(hxBean.data.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
//                                                helper?.setText(R.id.itemName,hxBean?.data.user_nickname)
//                                            }
//                                        }
//                                    }
//
//                                    override fun onCacheSuccess(response: Response<HXBean>?) {
//                                        super.onCacheSuccess(response)
//                                        val hxBean = response?.body()
//                                        if (hxBean?.code==1){
//                                            if (hxBean?.data!=null){
//                                                Glide.with(mContext).load(hxBean.data.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
//                                                helper?.setText(R.id.itemName,hxBean?.data.user_nickname)
//                                            }
//                                        }
//                                    }
//                                })
/*头像昵称*/
                        Glide.with(mContext).load(item?.message!!.getStringAttribute("userIcon")).dontAnimate().into(helper?.getView(R.id.itemIcon))
                        helper?.setText(R.id.itemName,item?.message!!.getStringAttribute("userName"))
                        if (helper?.adapterPosition==0){
                            helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime!!))
                        }else{
                            if (MyUtils.secLeft(data[helper?.adapterPosition-1].message.msgTime,System.currentTimeMillis())>3000){
                                helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime!!))
                            }else{
                                helper?.setText(R.id.itemTime,"")
                            }
                        }
                        val btVoice = helper?.getView<RelativeLayout>(R.id.itemVoice)
                        val imageView = helper?.getView<ImageView>(R.id.itemImg)
                        imageView.background=resources.getDrawable(R.mipmap.ic_voice)
                        btVoice.setOnClickListener {
                            LogUtil.logi(item?.message?.body.toString())
                            val body = item?.message?.body as EMVoiceMessageBody
                            if (player.isPlaying){
                                player.pause()
                            }
                            player.playUrl(body?.remoteUrl.toString().split(",")[0])
                            player.setOverListener {
                                animDrawable.stop()
                                imageView.background=resources.getDrawable(R.mipmap.ic_voice)

                            }
                            imageView.background=animDrawable
                            animDrawable.start()
                            LogUtil.logi("播放的链接${body?.remoteUrl.toString().split(",")[0]}")
                            val message = item?.message
                            if (message.from.equals(owner)){
                                helper?.setVisible(R.id.btGive,true)
                            }else{
                                helper?.setVisible(R.id.btGive,false)
                            }
                        }
                    }
                    4->{

                        /*头像*/
//                        OkGo.post<HXBean>(Urls.BaseUrl+Urls.HX_USER)
//                                .cacheKey("icon${item?.message?.from}")
//                                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
//                                .headers("token", SPHelper.getToken(this@JiePanDetailAty))
//                                .params("hx_user_name",item?.message?.from)
//                                .execute(object :JsonCallBack<HXBean>(){
//                                    override fun onSuccess(response: Response<HXBean>?) {
//                                        val hxBean = response?.body()
//                                        if (hxBean?.code==1){
//                                            if (hxBean?.data!=null){
//                                                Glide.with(mContext).load(hxBean.data.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
//                                                helper?.setText(R.id.itemName,hxBean?.data.user_nickname)
//                                            }
//                                        }
//                                    }
//
//                                    override fun onCacheSuccess(response: Response<HXBean>?) {
//                                        super.onCacheSuccess(response)
//                                        val hxBean = response?.body()
//                                        if (hxBean?.code==1){
//                                            if (hxBean?.data!=null){
//                                                Glide.with(mContext).load(hxBean.data.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
//                                                helper?.setText(R.id.itemName,hxBean?.data.user_nickname)
//                                            }
//                                        }
//                                    }
//                                })
                        if (helper?.adapterPosition==0){
                            helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime!!))
                        }else{
                            if (MyUtils.secLeft(data[helper?.adapterPosition-1].message.msgTime,System.currentTimeMillis())>3000){
                                helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime!!))
                            }else{
                                helper?.setText(R.id.itemTime,"")
                            }
                        }
                        /*视频消息*/
                        val body = item?.message!!.body as EMVideoMessageBody
                        /*头像昵称*/
                        Glide.with(mContext).load(item?.message.getStringAttribute("userIcon")).dontAnimate().into(helper?.getView(R.id.itemIcon))
                        helper?.setText(R.id.itemName,item?.message.getStringAttribute("userName"))
                        val split = body.thumbnailUrl.split("/")
                        val img = helper?.getView<ImageView>(R.id.itemImg)
                        LogUtil.logi(body.remoteUrl)
                        Glide.with(mContext).load(Urls.HX_URL+ split[split.size-1]).asBitmap()
                                .into(object :SimpleTarget<Bitmap>(){
                                    override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {
                                        LogUtil.e("fhp","宽${resource?.width}")
                                        LogUtil.e("fhp","高${resource?.height}")
                                        img.setImageBitmap(BitmapCut.cutBitmap(resource))
                                        recyclerview.scrollToPosition(messageLists.size-1)
                                    }
                                })
                        val bg = helper?.getView<TextView>(R.id.bg)
                        val tvProgress = helper?.getView<TextView>(R.id.tvProgress)
                        val btPlay = helper?.getView<ImageView>(R.id.btPlay)
                        if (!File("/storage/emulated/0/download/"+body!!.fileName).exists()){
                            OkGo.get<File>(body?.remoteUrl)
                                    .execute(object :FileCallback("/storage/emulated/0/download/",body!!.fileName){
                                        override fun onSuccess(response: Response<File>?) {
                                            val file = response!!.body()
                                            bg.visibility=View.GONE
                                            tvProgress.visibility=View.GONE
                                            btPlay.visibility=View.VISIBLE
                                            LogUtil.logi("下载成功${file.path}")
                                            btPlay.setOnClickListener {
                                                LogUtil.logi("----${body.toString()}")
                                                val intent = Intent(this@JiePanDetailAty, VideoPreViewAty::class.java)
                                                intent.putExtra("img",Urls.HX_URL+split[split.size-1])
                                                intent.putExtra("video",file.path)
                                                startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this@JiePanDetailAty,img,"img").toBundle())

                                            }
                                        }
                                        override fun downloadProgress(progress: Progress?) {
                                            LogUtil.logi("下载进度${MyUtils.formatDouble(progress!!.fraction.toDouble(),1)}")
                                            bg.visibility=View.VISIBLE
                                            tvProgress.visibility=View.VISIBLE
                                            btPlay.visibility=View.GONE
                                            tvProgress.text=MyUtils.formatDouble((progress!!.currentSize/progress!!.totalSize).toDouble(),2)+"%"
                                        }

                                    })
                        }else{
                            bg.visibility=View.GONE
                            tvProgress.visibility=View.GONE
                            btPlay.visibility=View.VISIBLE
                            btPlay.setOnClickListener {
                                LogUtil.logi("----${body.toString()}")
                                val intent = Intent(this@JiePanDetailAty, VideoPreViewAty::class.java)
                                intent.putExtra("img",Urls.HX_URL+split[split.size-1])
                                intent.putExtra("video","/storage/emulated/0/download/${body?.fileName}")
                                startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this@JiePanDetailAty,img,"img").toBundle())

                            }
                        }
                    }
                    11->{
                        val bean = SPHelper.getUser(mContext) as UserInfoBean.DataBean
//                        Glide.with(mContext).load(bean?.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
//                        helper?.setText(R.id.itemName,bean?.user_nickname)
                        LogUtil.logi("自己文字消息")
                        val body = item?.message?.body as EMTextMessageBody
                        Glide.with(mContext).load(item?.message.getStringAttribute("userIcon")).dontAnimate().into(helper?.getView(R.id.itemIcon))
                        helper?.setText(R.id.itemName,item?.message.getStringAttribute("userName"))
                        val itemContent = helper?.getView<TextView>(R.id.itemContent)
                        itemContent.text=body.message
                        if (helper?.adapterPosition==0){
                            helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                        }else{
                            if (MyUtils.secLeft(data[helper?.adapterPosition-1].message.msgTime,System.currentTimeMillis())>3000){
                                helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                            }else{
                                helper?.setText(R.id.itemTime,"")
                            }
                        }
                        //处理表情
                        var tmpStr = itemContent.text.toString()
                        for (i in 0 ..EaseDefaultEmojiconDatas.emojis.size-1){
                            if (tmpStr.contains(EaseDefaultEmojiconDatas.emojis[i])){
//                                val tmpStr = itemContent.text.toString()
                                val emojiText = EaseDefaultEmojiconDatas.emojis[i]
                                var emji="<img src=\""+EaseDefaultEmojiconDatas.icons[i]+"\"/>"
                                tmpStr = tmpStr.replace(emojiText, emji)
                                LogUtil.logi("处理表情后${tmpStr}")
                            }
                        }
                        itemContent.text=Html.fromHtml(tmpStr,imgGetterFromProject,null)
                        /* ************************************************************/
                    }
                    21->{
                        val bean = SPHelper.getUser(mContext) as UserInfoBean.DataBean
                        Glide.with(mContext).load(bean?.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
                        helper?.setText(R.id.itemName,bean?.user_nickname)
                        val messageBody = item?.message?.body as EMImageMessageBody
                        LogUtil.log("自己图片信息${messageBody}")
                        Glide
                                .with(mContext)
                                .load(messageBody.localUrl)
                                .thumbnail(0.3f)
                                .into(helper?.getView(R.id.itemImg))
                        val btImg = helper?.getView<ImageView>(R.id.itemImg)
                        if (helper?.adapterPosition==0){
                            helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                        }else{
                            if (MyUtils.secLeft(data[helper?.adapterPosition-1].message.msgTime,System.currentTimeMillis())>3000){
                                helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime))
                            }else{
                                helper?.setText(R.id.itemTime,"")
                            }
                        }
                        btImg.setOnClickListener {
                            val intent = Intent(this@JiePanDetailAty, ImagePreviewAty::class.java)
                            intent.putExtra("img",messageBody.localUrl)
                            startActivity(intent)
                        }
                    }
                    31->{
                        val bean = SPHelper.getUser(mContext) as UserInfoBean.DataBean
                        Glide.with(mContext).load(bean?.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
                        helper?.setText(R.id.itemName,bean?.user_nickname)
                        LogUtil.logi("进来设置了3")
                        val btVoice = helper?.getView<RelativeLayout>(R.id.itemVoice)
                        val imageView = helper?.getView<ImageView>(R.id.itemImg)
                        imageView.background=resources.getDrawable(R.mipmap.ic_voice)
                        if (helper?.adapterPosition==0){
                            helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime!!))
                        }else{
                            if (MyUtils.secLeft(data[helper?.adapterPosition-1].message.msgTime,System.currentTimeMillis())>3000){
                                helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime!!))
                            }else{
                                helper?.setText(R.id.itemTime,"")
                            }
                        }
                        btVoice.setOnClickListener {
                            LogUtil.logi(item?.message?.body.toString())
                            val body = item?.message?.body as EMVoiceMessageBody
                            if (player.isPlaying){
                                player.pause()
                            }
                            player.playUrl(body?.remoteUrl.toString().split(",")[0])
                            player.setOverListener {
                                LogUtil.e("fhp","Over!!!!!音频")
                                animDrawable.stop()
                                imageView.background=resources.getDrawable(R.mipmap.ic_voice)

                            }
                            imageView.background=animDrawable
                            animDrawable.start()
                            notifyDataSetChanged()
                            LogUtil.logi("播放的链接${body?.remoteUrl.toString().split(",")[0]}")
                        }
                    }
                    41->{
                        /*自己信息*/
                        val bean = SPHelper.getUser(mContext) as UserInfoBean.DataBean
                        if (helper?.adapterPosition==0){
                            helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime!!))
                        }else{
                            if (MyUtils.secLeft(data[helper?.adapterPosition-1].message.msgTime,System.currentTimeMillis())>3000){
                                helper?.setText(R.id.itemTime,MyUtils.timeStampToStr(item?.message?.msgTime!!))
                            }else{
                                helper?.setText(R.id.itemTime,"")
                            }
                        }
                        Glide.with(mContext).load(bean?.avatar).dontAnimate().into(helper?.getView(R.id.itemIcon))
                        helper?.setText(R.id.itemName,bean?.user_nickname)
                        /*视频*/
                        LogUtil.logi("进入发送视频消息回调")
                        val body = item?.message!!.body as EMVideoMessageBody
                        val thumb = body.toString().split("thumbnailUrl: ")[1].split(",")[0]
                        val split = body.thumbnailUrl.split("/")
                        val img = helper?.getView<ImageView>(R.id.itemImg)
                        val bg = helper?.getView<TextView>(R.id.bg)
                        val tvProgress = helper?.getView<TextView>(R.id.tvProgress)
                        val btPlay = helper?.getView<ImageView>(R.id.btPlay)
                        Glide.with(mContext).load(thumb)
                                .asBitmap()
                                .into(object :SimpleTarget<Bitmap>(){
                                    override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {
                                        LogUtil.e("fhp","宽${resource?.width}")
                                        LogUtil.e("fhp","高${resource?.height}")
                                        img.setImageBitmap(BitmapCut.cutBitmap(resource))
                                        recyclerview.scrollToPosition(messageLists.size-1)

                                    }
                                })

                        LogUtil.logi("词条消息是否发送过${item?.message.isDelivered}")
                            if (!item?.message.isDelivered){
                                LogUtil.logi("设置监听")
                                item?.message.setMessageStatusCallback(object :EMCallBack{
                                    override fun onSuccess() {
                                        LogUtil.logi("发送成功")
                                        runOnUiThread {
                                            bg.visibility=View.GONE
                                            tvProgress.visibility=View.GONE
                                            btPlay.visibility=View.VISIBLE
                                            btPlay.setOnClickListener {
                                                val intent = Intent(this@JiePanDetailAty, VideoPreViewAty::class.java)
                                                intent.putExtra("img",Urls.HX_URL+split[split.size-1])
                                                intent.putExtra("video",body.localUrl)
                                                startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this@JiePanDetailAty,img,"img").toBundle())
                                            }
                                        }
                                    }

                                    override fun onProgress(p0: Int, p1: String?) {
                                        LogUtil.logi("发送进度${p0}${p1}")
                                        runOnUiThread {
                                            bg.visibility=View.VISIBLE
                                            tvProgress.visibility=View.VISIBLE
                                            btPlay.visibility=View.GONE
                                            tvProgress.text="${p0}%"
                                        }
                                    }

                                    override fun onError(p0: Int, p1: String?) {
//                                LogUtil.logi("发送失败")
                                        MyUtils.toast("视频发送失败")
                                    }
                                })
                                LogUtil.logi("适配器理发")
                                sendMessage(item?.message)
                                item?.message.isDelivered=true
                            }else{
                                LogUtil.logi("跳过设置监听")
                                bg.visibility=View.GONE
                                tvProgress.visibility=View.GONE
                                btPlay.visibility=View.VISIBLE

                                btPlay.setOnClickListener {
                                    val intent = Intent(this@JiePanDetailAty, VideoPreViewAty::class.java)
                                    intent.putExtra("img",Urls.HX_URL+split[split.size-1])
                                    intent.putExtra("video",body.localUrl)
                                    startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this@JiePanDetailAty,img,"img").toBundle())
                                }
                            }
                    }
                }
            }

        }
        recyclerview.adapter=adp
        recyclerview.layoutManager=LinearLayoutManager(this,LinearLayout.VERTICAL,false)
    }

    private val PICK_VIDEO: Int=100
    private val PICK_IMAGE: Int=111

    /**
     * 输入框是能
     */
    private fun initInput() {
        input_menu.init()
        input_menu.registerExtendMenuItem("相册", R.drawable.ease_chat_image_selector, 1, object : EaseChatExtendMenu.EaseChatExtendMenuItemClickListener{
            override fun onClick(itemId: Int, view: View?) {
                when(itemId){
                    1->{
                        Matisse.from(this@JiePanDetailAty)
                                .choose(MimeType.ofAll())
                                .showSingleMediaType(true)
                                .countable(true)
                                .maxSelectable(1)
                                .spanCount(3)
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                .thumbnailScale(0.85f)
                                .theme(R.style.Matisse_Dracula)
                                .imageEngine( GlideEngine())
                                .forResult(PICK_IMAGE);
//                        selectPicFromCamera()
                    }
                }
            }
        })
        input_menu.registerExtendMenuItem("拍照",R.drawable.ease_chat_takepic_normal,2,object :EaseChatExtendMenu.EaseChatExtendMenuItemClickListener{
            override fun onClick(itemId: Int, view: View?) {
                when(itemId){
                    2->{

                        val intent = Intent(this@JiePanDetailAty, CameraAty::class.java)
                        intent.putExtra("type",2)
                        startActivity(intent)
                       /* Matisse.from(this@JiePanDetailAty)
                                .choose(MimeType.ofAll())
                                .showSingleMediaType(true)
                                .countable(true)
                                .maxSelectable(1)
                                .spanCount(3)
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                .thumbnailScale(0.85f)
                                .theme(R.style.Matisse_Dracula)
                                .imageEngine( GlideEngine())
                                .forResult(PICK_VIDEO);*/
                    }
                }
            }
        })
        input_menu.registerExtendMenuItem("视频",R.mipmap.ic_shexiang,2,object :EaseChatExtendMenu.EaseChatExtendMenuItemClickListener{
            override fun onClick(itemId: Int, view: View?) {
                when(itemId){
                    2->{
                        val intent = Intent(this@JiePanDetailAty, CameraAty::class.java)
                        intent.putExtra("type",1)
                        startActivity(intent)
                    }
                }
            }
        })
        input_menu.setChatInputMenuListener(object :EaseChatInputMenu.ChatInputMenuListener{
            override fun onSendMessage(content: String?) {
                sendTextMessage(content!!)
            }

            override fun onBigExpressionClicked(emojicon: EaseEmojicon?) {
//                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onPressToSpeakBtnTouch(v: View?, event: MotionEvent?): Boolean {
         /*       if (event?.action==MotionEvent.ACTION_DOWN){
                    LogUtil.e("fhp","执行了嘛？")
                    voice_recorder.visibility=View.VISIBLE
                }else if (event?.action==MotionEvent.ACTION_UP){
                    LogUtil.e("fhp","执行了嘛2？")
                    voice_recorder.visibility=View.GONE
                }*/
                return voice_recorder.onPressToSpeakBtnTouch(v, event, object : EaseVoiceRecorderView.EaseVoiceRecorderCallback {

                    override fun onVoiceRecordComplete(voiceFilePath: String, voiceTimeLength: Int) {
                        sendVoice(voiceFilePath, voiceTimeLength)
                    }
                })

            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        player.stop()
        EventBus.getDefault().unregister(this)
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }

    override fun onPause() {
        super.onPause()
        player.pause()
    }
    /**
     * capture new image
     */
    protected fun selectPicFromCamera() {
        if (!EaseCommonUtils.isSdcardExist()) {
            Toast.makeText(this, com.hyphenate.easeui.R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT).show()
            return
        }

        cameraFile = File(PathUtil.getInstance().imagePath, EMClient.getInstance().currentUser
                + System.currentTimeMillis() + ".jpg")

        cameraFile.getParentFile().mkdirs()
        startActivityForResult(
                Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!=-1)return
        when(requestCode){
            REQUEST_CODE_CAMERA->{
                if (cameraFile != null && cameraFile.exists())
                    LogUtil.logi("发送")
                    sendImageMessage(cameraFile.absolutePath)
            }
            PICK_VIDEO->{
                val obtainPathResult = Matisse.obtainPathResult(data)
                LogUtil.log(obtainPathResult[0])
                val file = File(obtainPathResult[0])
                val media = MediaMetadataRetriever()
                media.setDataSource(file.path)
                val imageFile = MyUtils.createImageFile(media.frameAtTime)
                LogUtil.logi("选择的图片路径${imageFile.path}")

                sendVideo(obtainPathResult[0],imageFile.path,media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION).toInt())
            }
            PICK_IMAGE->{
                val obtainPathResult = Matisse.obtainPathResult(data)
                if (MediaFile.isVideoFileType(obtainPathResult[0])){
                    val file = File(obtainPathResult[0])
                    val media = MediaMetadataRetriever()
                    media.setDataSource(file.path)
                    val imageFile = MyUtils.createImageFile(media.frameAtTime)
                    LogUtil.logi("选择的图片路径${imageFile.path}")

                    sendVideo(obtainPathResult[0],imageFile.path,media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION).toInt())
                }else if (MediaFile.isIMG(obtainPathResult[0])){
                    sendImageMessage(obtainPathResult[0])
                }
            }
        }
    }
    override fun initListener() {
        btExit.setOnClickListener {
            finish()
        }
        btShare.setOnClickListener {
            val listener=object : PlatformActionListener {
                override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
                    OkGo.post<BaseBean>(Urls.BaseUrl+Urls.SHARE)
                            .execute(object :JsonCallBack<BaseBean>(this@JiePanDetailAty){
                                override fun onSuccess(response: Response<BaseBean>?) {
                                    val bean = response?.body()
                                    if (bean?.code==1){
                                        ToastUtils.toast(this@JiePanDetailAty,"分享成功")
                                    }else{
                                        ToastUtils.toast(this@JiePanDetailAty,bean?.msg!!)
                                    }
                                }
                            })
                }
                override fun onCancel(p0: Platform?, p1: Int) {
                    ToastUtils.toast(this@JiePanDetailAty,"分享已取消")
                }
                override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                    ToastUtils.toast(this@JiePanDetailAty,"分享失败")
                }
            }
            val oks = OnekeyShare()
            oks.callback=listener
            oks.setTitle(tv_title.text.toString())
            // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
            oks.setTitleUrl("https://www.baidu.com/")
            // text是分享文本，所有平台都需要这个字段
            oks.text = "解盘直播，学会怎么赚钱"
            //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
            oks.setImageUrl("http://zhishang.hlhjapp.com/static/images/logo.png")
            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
            //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
            // url仅在微信（包括好友和朋友圈）中使用
            oks.setUrl("https://www.baidu.com/")
            // comment是我对这条分享的评论，仅在人人网和QQ空间使用
            oks.show(this)
        }

    }
    protected fun sendTextMessage(text:String){
        val message = EMMessage.createTxtSendMessage(text, toChatUsername)
        message.setAttribute("userIcon",userInfo.avatar)
        message.setAttribute("userName",userInfo.user_nickname)
        message.chatType=EMMessage.ChatType.ChatRoom

        val m = CustomMessage()
        m.message=message
        m.type=11
        messageLists.add(m)
        adp.notifyDataSetChanged()
        recyclerview.scrollToPosition(messageLists.size-1)
        Thread(Runnable {
            EMClient.getInstance().chatManager().sendMessage(message);
        }).start()
    }
    /*发送图片*/
    protected fun sendImageMessage(imagePath: String) {
        val message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername)
            message.setChatType(EMMessage.ChatType.GroupChat);
        message.setAttribute("userIcon",userInfo.avatar)
        message.setAttribute("userName",userInfo.user_nickname)
        LogUtil.logi("消息发出${toChatUsername}-----${imagePath}")
        EMClient.getInstance().chatManager().sendMessage(message);
        val m = CustomMessage()
        m.message=message
        m.type=21
        messageLists.add(m)
        adp.notifyDataSetChanged()
        recyclerview.scrollToPosition(messageLists.size-1)
    }
    /*语音消息*/
    protected fun sendVoice(filePath:String,length:Int){
        val message = EMMessage.createVoiceSendMessage(filePath, length, toChatUsername)
        message.setAttribute("userIcon",userInfo.avatar)
        message.setAttribute("userName",userInfo.user_nickname)
        sendMessage(message)
        val m = CustomMessage()
        m.message=message
        m.type=31
        messageLists.add(m)
        adp.notifyDataSetChanged()
        recyclerview.scrollToPosition(messageLists.size-1)
    }
    /*发送视频*/
    protected fun sendVideo(path:String,thumb:String,length:Int){
        val message = EMMessage.createVideoSendMessage(path, thumb, length, toChatUsername)
        message.setAttribute("userIcon",userInfo.avatar)
        message.setAttribute("userName",userInfo.user_nickname)
//        sendMessage(message)
        val m = CustomMessage()
        m.message=message
        m.type=41
        messageLists.add(m)
        adp.notifyDataSetChanged()
//        sendMessage(message)
    }
    private fun sendMessage(message: EMMessage){
        message.chatType=EMMessage.ChatType.ChatRoom
        message.setAttribute("userIcon",userInfo.avatar)
        message.setAttribute("userName",userInfo.user_nickname)
        Thread(Runnable {
            EMClient.getInstance().chatManager().sendMessage(message);
        }).start()
    }


    /*Event*/
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun handEvent(tempBean: TempBean){
        if (tempBean.type==110){
            val imageFile = MyUtils.createImageFile(tempBean.bitmap)
            val file = File(tempBean.path)
            val media = MediaMetadataRetriever()
            media.setDataSource(file.path)
            sendVideo(tempBean.path,imageFile.path,media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION).toInt())

        }else if (tempBean.type==120){
            val imageFile = MyUtils.createImageFile(tempBean.bitmap)
            sendImageMessage(imageFile.path)
        }
    }

}
